package com.neu.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class FilterDemo implements Filter {
	/**
	 *  过滤器完成初始化需要
	 */
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("开始执行初始化.....");
	}
	/**
	 *  过滤器完成初始化需要执行的方法    
	 */
	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		System.out.println("开始执行过滤......");
		/**
		 * 将 ServletRequest 转换成可以支持Http协议的接口HttpServletRequest
		 */
		HttpServletRequest request = (HttpServletRequest) arg0;
		/**
		 * 将 ServletResponse 转换成可以支持Http协议的接口HttpServletResponse
		 */
		HttpServletResponse response = (HttpServletResponse) arg1;
		/**
		 * 拦截请求 将请求的编码集设定为 utf-8
		 */
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=UTF-8");
		System.out.println("过滤完成，但是不放行");
		/**
		 * 如果开发者想要放行过滤后的请求
		 */
		arg2.doFilter(request, response);		
	}
		
	/**
	 *  过滤器销毁时要执行的方法
	 */
		@Override
		public void destroy() {
			System.out.println("执行销毁......");
		}
}
